from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
from selenium_get_logined_driver import *
# 两种导入方式的区别，上面这种可以直接调用包里面定义的函数，下面这个需要通过包名.方法的形式调用
# import selenium_get_logined_driver
import time



driver = get_browser_2()
# driver = get_browser_3()
driver.get("https://www.bilibili.com")

# driver.implicitly_wait(10)
wait = WebDriverWait(driver, 10)

link_xpath = '//div[@class="recommended-container_floor-aside"]/div[contains(@class, "container")]/div[@class="feed-card"][1]'
element = wait.until(EC.presence_of_element_located((By.XPATH, link_xpath)))
element.click()

# 多窗口切换
time.sleep(1)
handles = driver.window_handles

# 窗口切换后并不能像切换iframe后那样通过switch_to.default_content()返回主文档，所以可以在切换窗口前记录原来的窗口句柄
# main_handle = driver.current_window_handle

driver.switch_to.window(handles[1])  # 因为b站视频链接是打开新选项卡，所以要将驱动器切换过去
# 当需要回到原来窗口时
# driver.switch_to.window(main_handle)

# driver.switch_to.frame(driver.find_element_by_xpath('//iframe[@id="bilibiliPlayer"]'))
# 当需要从iframe退回到原来主文档时
# driver.switch_to.default_content() 

element = wait.until(EC.presence_of_element_located((By.XPATH, '//input[@class="bpx-player-dm-input"]')))

element.send_keys('selenium测试弹幕')

element = wait.until(EC.presence_of_element_located((By.XPATH, '//div[contains(@class, "bpx-player-dm-btn-send")]/div')))
element.click()

time.sleep(3) # shadow dom要执行js脚本，还不知道如何利用selenium的等待机制，所以先用这个方案等待

# shadow dom处理：先在浏览器控制台右键元素节点，copy->js path得到获取该节点的js代码，然后用驱动器执行js代码拿到这个节点
element = driver.execute_script('''
  return document.querySelector("#commentapp > bili-comments").shadowRoot.querySelector("#header > bili-comments-header-renderer").shadowRoot.querySelector("#commentbox > bili-comment-box").shadowRoot.querySelector("#editor > bili-comment-rich-textarea").shadowRoot.querySelector("#input > div > div.brt-editor")
''')
element.send_keys('selenium测试评论')

element = driver.execute_script('''
  return document.querySelector("#commentapp > bili-comments").shadowRoot.querySelector("#header > bili-comments-header-renderer").shadowRoot.querySelector("#commentbox > bili-comment-box").shadowRoot.querySelector("#pub > button")
''')
element.click()

# element.clear()
# element.text = 'selenium测试评论'
# element.get_attribute('value')
# element.get_attribute('outerHTML')
# element.get_attribute('innerText')
# element.get_attribute('textContent')
# element.select_by_value('1')
# element.select_by_index(0)
# driver.find_element(By.CSS_SELECTOR, 'div')
# driver.switch_to.alert.accept()

# 动作链，鼠标移动到某个元素上
# ac = ActionChains(driver)
# ac.move_to_element(element).perform()

time.sleep(10)

driver.quit()


